package org.penguin.study.bk.organization.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.penguin.study.bk.base.query.QueryGenerator;
import org.penguin.study.bk.base.vo.Result;
import org.penguin.study.bk.constant.HttpStatus;
import org.penguin.study.bk.organization.entity.Organization;
import org.penguin.study.bk.organization.service.OrganizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author chengyinghua
 */
@Slf4j
@Tag(name = "组织控制器", description = "组织信息")
@RestController
@RequestMapping("/organization")
public class OrganizationController {

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * @return
     * @功能：新增
     */
    @Operation(summary = "组织表-新增组织", description = "组织表-新增组织")
    @PostMapping(value = "/add")
    public Result<Organization> add(@RequestBody Organization organization) {
        Result<Organization> result = new Result<>();
        try {
            organization.setCreatedBy("admin");
            organization.setCreatedTime(LocalDateTime.now());
            organizationService.createOrUpdate(organization);
            result.success("保存成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * @return
     * @功能：新增
     */
    @Operation(summary = "组织表-新增组织", description = "组织表-新增组织")
    @PutMapping(value = "/update")
    public Result<Organization> update(@RequestBody Organization organization) {
        Result<Organization> result = new Result<>();
        try {
            organization.setUpdatedBy("admin");
            organization.setUpdatedTime(LocalDateTime.now());
            organizationService.createOrUpdate(organization);
            result.success("保存成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    @GetMapping(value = "/list")
    public Result<?> queryPageList(Organization organization,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize",
            defaultValue = "10") Integer pageSize, HttpServletRequest request) {

        QueryWrapper<Organization> queryWrapper = QueryGenerator.initQueryWrapper(organization, request.getParameterMap());
        Page<Organization> page = new Page<>(pageNo, pageSize);
        IPage<Organization> pageList = organizationService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    @GetMapping(value = "/detail/{organizationId}")
    public Result<?> getById(@PathVariable("organizationId") String organizationId) {
        Organization organization = organizationService.getById(organizationId);
        if (organization == null) {
            return Result.error(HttpStatus.Not_Found, String.format("您要的对象(Id: %s)，已经被删除", organizationId));
        }
        return Result.ok(organization);
    }

    @DeleteMapping(value = "/{organizationId}/delete")
    public Result<?> deleteById(@PathVariable("organizationId") String organizationId) {
        Organization foundOrganization = organizationService.getById(organizationId);
        if (foundOrganization == null) {
            return Result.error(HttpStatus.Not_Found, String.format("根据Id: %s，找不到匹配的对象", organizationId));
        }
        organizationService.delete(foundOrganization);
        return Result.ok("删除成功", foundOrganization);
    }

    @GetMapping("/redis/keys")
    public Result<?> printRedis() {
        Map<String, Object> map = new HashMap<>(1);
        Set<String> keys = redisTemplate.keys("*");
        for (String key : keys) {
            map.put(key, redisTemplate.opsForValue().get(key));
        }
        return Result.ok(map);
    }

}
